﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using System.Runtime.Caching;
using Gollie.WebCache;

namespace Gollie
{
	public static class Helper
	{
		public static string GetImageSrcAttribute(string filePath)
		{
			try
			{
				if (string.IsNullOrEmpty(filePath))
					return "";

				string key = "imgdata_" + filePath;
				string dataUrl = (string)DataCache.Cache[key];

				if (dataUrl == null)
				{
					byte[] allBytes = File.ReadAllBytes(filePath);
					string b64 = Convert.ToBase64String(allBytes, 0, allBytes.Length);
					string mime = Gollie.Mime.MimeMapping.GetMimeMapping(Path.GetExtension(filePath));
					int b64Length = 5 + 32 + 8 + 4 * (allBytes.Length / 3 + 1);
					StringBuilder str = new StringBuilder("data:", b64Length);
					str.Append(mime);
					str.Append(";base64,");
					str.Append(b64);

					dataUrl = str.ToString();

					CacheItemPolicy policy = CacheDependencyBase.CreatePolicy(filePath);
					policy.AbsoluteExpiration = DateTime.Now.AddHours(1);

					DataCache.Insert(key, dataUrl, policy);
				}

				return dataUrl;
			}
			catch (Exception)
			{
				return "";
			}
		}

		/// <summary>
		/// Make sure the logged in vendor owns the invoices
		/// </summary>
		/// <param name="pdfPath"></param>
		/// <returns></returns>
		public static bool IsAuthorizedForInvoice(string pdfPath, uint vendorId)
		{
			string[] folders = pdfPath.Split(System.IO.Path.DirectorySeparatorChar);
			if (folders.Length < 2)
				return false;

			uint pathVid = Convert.ToUInt32(folders[folders.Length - 2]);

			return vendorId == pathVid;
		}

		/// <summary>
		/// Converts a string to decimal
		/// </summary>
		/// <param name="amount"></param>
		/// <returns></returns>
		public static decimal GetDecimal(string amount)
		{
			string s = amount.Replace('.', ',');
			int commaCount = s.Count(p => p == ',');
			if (commaCount > 1)
				throw new FormatException("Incorrect bedrag");

			decimal val;
			if (decimal.TryParse(s, out val) == false)
				throw new FormatException("Incorrect bedrag");

			return val;
		}

	}
}